<template>
  <div class="home-page">
    <!-- 导航栏 -->
    <nav class="navbar">
      <div class="logo">
        <span class="logo-text">快递面单录入系统</span>
      </div>
      <div class="user-info">
        <span>{{ currentUser?.username || '用户' }}</span>
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </div>
    </nav>
    
    <!-- 主内容区域 -->
    <div class="main-content">
      <div class="container">
        <!-- 页面标题和操作栏 -->
        <div class="page-header">
          <h1>地址簿</h1>
          <div class="action-bar">
            <button class="batch-delete-btn" @click="handleBatchDelete">批量删除</button>
            <button class="new-address-btn" @click="goToNewAddress">新建地址</button>
          </div>
        </div>
        
        <!-- 地址列表 -->
        <div v-if="addresses.length > 0" class="address-list">
          <div 
            v-for="address in addresses" 
            :key="address.id" 
            class="address-item"
            :data-id="address.id"
            @click="handleItemClick($event, address)"
          >
            <div class="address-header">
              <span class="contact-name">{{ address.name || '未命名' }}</span>
              <span class="contact-phone">{{ formatPhone(address.phone) }}</span>
              <label class="checkbox-container" @click.stop>
                <input 
                  type="checkbox" 
                  class="address-checkbox"
                  :value="address.id"
                  v-model="selectedIds"
                >
                <span class="checkmark"></span>
              </label>
            </div>
            <div class="address-content">
              <span class="address-text">{{ getFullAddress(address) }}</span>
              <span class="create-time">{{ formatTime(address.createdAt) }}</span>
            </div>
          </div>
        </div>
        
        <!-- 空状态提示 -->
        <div v-else class="empty-state">
          <h3>暂无地址信息</h3>
          <p>点击"新建地址"按钮添加第一个地址</p>
        </div>
      </div>
    </div>
    
    <!-- 页脚 -->
    <div class="footer">
      <p>2025 ©523300264225徐烨</p>
      <p>J2EE程序设计-快递面单录入系统</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { addressAPI } from '../api'

const router = useRouter()
const currentUser = ref(null)
const addresses = ref([])
const selectedIds = ref([])

onMounted(() => {
  const user = JSON.parse(sessionStorage.getItem('currentUser') || 'null')
  if (!user) {
    router.push('/login')
    return
  }
  currentUser.value = user
  loadAddresses()
})

const loadAddresses = async () => {
  try {
    const response = await addressAPI.getAll()
    if (response.success) {
      addresses.value = response.data || []
      // 按创建时间倒序排列
      addresses.value.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
    }
  } catch (error) {
    console.error('加载地址失败:', error)
  }
}

const formatPhone = (phone) => {
  if (!phone) return '未提供手机号'
  if (phone.length === 11) {
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1 **** $2')
  }
  return phone
}

const getFullAddress = (address) => {
  return `${address.province || ''}${address.city || ''}${address.district || ''}${address.detailAddress || ''}`
}

const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    alert('请选择要删除的地址')
    return
  }
  
  if (!confirm(`确定要删除选中的 ${selectedIds.value.length} 个地址吗？`)) {
    return
  }
  
  try {
    const response = await addressAPI.delete(selectedIds.value)
    if (response.success) {
      alert('删除成功！')
      selectedIds.value = []
      loadAddresses()
    } else {
      alert(response.message || '删除失败')
    }
  } catch (error) {
    alert('删除失败，请稍后重试')
  }
}

const handleItemClick = (event, address) => {
  // 点击地址项时，可以跳转到编辑页面（暂时不实现）
  console.log('编辑地址 ID:', address.id)
}

const handleLogout = () => {
  sessionStorage.removeItem('currentUser')
  sessionStorage.removeItem('authToken')
  router.push('/login')
}

const goToNewAddress = () => {
  router.push('/new-address')
}
</script>

<style scoped>
.home-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  padding-bottom: 1rem;
  border-bottom: 2px solid #f0f0f0;
}

.page-header h1 {
  color: #333;
  font-size: 2rem;
  font-weight: 600;
}

.action-bar {
  display: flex;
  gap: 15px;
}

.batch-delete-btn, .new-address-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.batch-delete-btn {
  background: #dc3545;
  color: white;
}

.batch-delete-btn:hover {
  background: #c82333;
  transform: translateY(-2px);
}

.new-address-btn {
  background: #007bff;
  color: white;
}

.new-address-btn:hover {
  background: #0056b3;
  transform: translateY(-2px);
}

.address-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.address-item {
  background: #f8f9fa;
  border: 2px solid #e9ecef;
  border-radius: 12px;
  padding: 1.5rem;
  transition: all 0.3s ease;
  position: relative;
  cursor: pointer;
}

.address-item:hover {
  border-color: #007bff;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.contact-name {
  font-size: 1.2rem;
  font-weight: 600;
  color: #333;
}

.contact-phone {
  color: #666;
  font-size: 1rem;
}

.checkbox-container {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.address-checkbox {
  display: none;
}

.checkmark {
  width: 20px;
  height: 20px;
  border: 2px solid #ddd;
  border-radius: 4px;
  display: inline-block;
  position: relative;
  transition: all 0.3s ease;
}

.address-checkbox:checked + .checkmark {
  background: #007bff;
  border-color: #007bff;
}

.address-checkbox:checked + .checkmark::after {
  content: '✓';
  color: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 14px;
  font-weight: bold;
}

.address-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.address-text {
  color: #555;
  font-size: 1rem;
  line-height: 1.5;
}

.create-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.empty-state {
  text-align: center;
  padding: 3rem 2rem;
  color: #666;
}


.empty-state h3 {
  font-size: 1.5rem;
  margin-bottom: 0.5rem;
  color: #333;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 1rem;
    text-align: center;
  }
  
  .address-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
  
  .address-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
}
</style>

